/**
 * 
 */
package org.mspring.mlog.web.module.ucenter.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mspring.mlog.api.weibo.tencent.service.TencentWeiboService;
import org.mspring.mlog.entity.Attachment;
import org.mspring.mlog.entity.Twitter;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.AttachmentService;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.service.TwitterService;
import org.mspring.mlog.service.security.UserService;
import org.mspring.mlog.support.resolver.QueryParam;
import org.mspring.mlog.support.resolver.SpaceUser;
import org.mspring.mlog.web.module.ucenter.AbstractUCenterWidget;
import org.mspring.mlog.web.query.TwitterQueryCriterion;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.persistence.support.Page;
import org.mspring.platform.persistence.support.Sort;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * @author Liu Jun
 * @since 2013-06-22
 * @description
 * @TODO
 */
@Widget
@RequestMapping("/u/{username}/admin")
public class UCenterAdmin_TwitterWidget extends AbstractUCenterWidget {
    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;
    @Autowired
    private TwitterService twitterService;
    @Autowired
    private TencentWeiboService tencentWeiboService;
    @Autowired
    private AttachmentService attachmentService;

    /**
     * 微博列表
     * 
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/twitter/list")
    public String list(@SpaceUser(pathVariable = "username") User user, @ModelAttribute Page<Twitter> twitterPage, @ModelAttribute Twitter twitter, @QueryParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (user == null) {
            return "/errors/404";
        }
        if (twitterPage == null) {
        	twitterPage = new Page<Twitter>();
        }
        twitterPage.setSort(new Sort("id desc", ""));
       
        if (twitter == null) {
        	twitter = new Twitter();
        }
   
        queryParams.put("author.id", user.getId());
        twitterPage = twitterService.listPage(new TwitterQueryCriterion(queryParams), twitterPage);
        model.addAttribute("postPage", twitterPage);
        return "/u/admin/twitter/list";
    }

    
    /**
     * 后台添加微博
     * 
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/twitter/add")
    @ResponseBody
    public ResponseEntity add(@RequestParam(required = false) String content, @RequestParam(required = false) Long attachment, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录");
            return rsp;
        }
        if (StringUtils.isBlank(content)) {
            rsp.setSuccess(false);
            rsp.setMessage("请输入要发表的内容");
            return rsp;
        }

        try {
            Twitter twitter = new Twitter();
            twitter.setAuthor(user);
            twitter.setContent(content);
            twitter.setIp(RequestUtils.getRemoteIP(request));
            if (attachment != null) {
                twitter.setImage(new Attachment(attachment));
            }

            Long id = twitterService.createTwitter(twitter);
            twitter = twitterService.get(id);

            // 绑定图片和twitter
            if (attachment != null) {
                attachmentService.setAttachmentFid(attachment, Attachment.AttachFrom.FROM_TWITTER, id);
            }

            if (twitter.getImage() != null && twitter.getImage().getId() != null && StringUtils.isBlank(twitter.getImage().getPath())) {
                Attachment image = attachmentService.get(twitter.getImage().getId());
                twitter.setImage(image);
            }

            rsp.setSuccess(true);
            rsp.setMessage("发表成功");
            rsp.put("twitter", new Twitter[] { twitter });
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            rsp.setSuccess(false);
            rsp.setMessage("发表内容失败");
            return rsp;
        }
    }
    
    
    /**
     * 删除微博
     * 
     * @param id
     * @param request
     * @param response
     * @return
     * @throws IOException 
     */
    @RequestMapping("/twitter/delete/{id}")
    @ResponseBody
    public void deleteTwitter( @PathVariable Long id,HttpServletRequest request, HttpServletResponse response) throws IOException {
    	PrintWriter out = response.getWriter();
    	try {
    	 	twitterService.remove(id);
    	out.write("{'state':'0'}");
    	} catch (Exception e) {
			out.write("{'state':'1'}");
			e.printStackTrace();
		}
    }
    
    
   
}
